package com.warm.xss.validator;

import com.warm.xss.anaotation.Xss;
import org.noear.solon.Utils;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;
import org.noear.solon.validation.Validator;

import java.util.regex.Pattern;

/**
 * xss注解验证器
 *
 * @author minliuhua
 */
public class XssValidator implements Validator<Xss> {

    @Override
    public String message(Xss anno) {
        return anno.message();
    }

    @Override
    public Result<Void> validateOfValue(Xss anno, Object val, StringBuilder tmp) {
        return verifyDo(anno, String.valueOf(val));
    }

    @Override
    public Result<Void> validateOfContext(Context ctx, Xss anno, String name, StringBuilder tmp) {
        String val = ctx.param(name);
        return verifyDo(anno, val);
    }

    private Result<Void> verifyDo(Xss anno, String val) {
        if (Utils.isBlank(val)) {
            return Result.succeed();
        }

        if (Pattern.compile("<(\\S*?)[^>]*>.*?|<.*? />").matcher(val).matches()) {
            return Result.failure();
        } else {
            return Result.succeed();
        }
    }
}
